package com.yang.strategy.impl;

import cn.hutool.json.JSONUtil;
import com.yang.domain.dto.RedisData;
import com.yang.strategy.CacheStrategy;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 * 缓存模板类
 * </p>
 * @author yang
 * @date 2023/7/23
 */
public abstract class AbstractCacheStrategyImpl implements CacheStrategy {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void setCache(String key, Object value, Long time, TimeUnit unit, boolean isLogicalExpire){
        if (!isLogicalExpire){
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
        }else {
            //1.将传递过来的对象封装成RedisData对象
            RedisData redisData = new RedisData();

            //2.设置值和逻辑过期时间
            redisData.setData(value);
            redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

            //3.写入redis
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
        }
    }

    @Override
    public abstract <R,ID> R getCache
            (String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback, Long time, TimeUnit unit);
}
